package aqs;

import lock.ThreadUtil;

import java.util.concurrent.locks.Lock;

/**
 * 验证同一时刻是否只有两个线程访问资源
 * 
 * @author insight
 * @since 2021/9/13
 */
public class TwinsLockTest {
    private static final Lock LOCK = new TwinsLock();
    
    public static void main(String[] args) {
        // 成对打印 说明按照预期工作
        for (int i = 0; i < 10; i++) {
            Worker w = new Worker();
            w.setDaemon(true);
            w.start();
        }

        for (int i = 0; i < 10; i++) {
            ThreadUtil.second(1);
            System.out.println();
        }
    }

    static class Worker extends Thread {
        @Override
        public void run() {
            while (true) {
                LOCK.lock();
                try {
                    ThreadUtil.second(1);
                    System.out.println(Thread.currentThread().getName());
                    ThreadUtil.second(1);
                } finally {
                    LOCK.unlock();
                }
            }
        }
    }
    
}